//
//  JCNSView.swift
//  JCTest3
//
//  Created by Chen on 10/10/2022.
//

import Cocoa

// 一个久坐进入全屏提醒的功能
// 涉及计时器，GCD，NSView， 全屏
class JCNSView: JCBaseBottomView {
    
    var timer: Timer?
    var countTimer: Timer? // 这个计时器用来倒计时的
    var currentIndex: Int = 5
    private lazy var alert = NSAlert()
    
    
//     = {
//        let countTimer = Timer.scheduledTimer(timeInterval: TimeInterval(1.0), target: self, selector: #selector(self.countTimerAction), userInfo: nil, repeats: true)
//        return countTimer
//    }()
    
    private lazy var fullImage: NSImageView = {
        var fullImage = NSImageView()
        fullImage.image = NSImage(named: "fullscreen")
        fullImage.isHidden = true
        return fullImage
    }()
    
    private lazy var startTimerButton: NSButton = {
        var startTimerButton = NSButton(frame: NSRect(x: 12, y: 12, width: 100, height: 40))
        startTimerButton.setButtonType(.momentaryChange)
        startTimerButton.title = "Start Timer"
        startTimerButton.alternateTitle = "Start Timer"
        startTimerButton.target = self
        startTimerButton.action = #selector(self.reStartTimer)
        return startTimerButton
    }()
    
//    private lazy var promptLabel: NSTextField = {
//        var promptLabel = NSTextField(frame: NSRect.zero)
//        promptLabel.stringValue = "坐了很久了，休息休息吧～"
//        promptLabel.textColor = NSColor(red: 0.8, green: 0.6, blue: 0.6, alpha: 1.0)
//        promptLabel.font = NSFont.systemFont(ofSize: 24)
//        promptLabel.isHidden = true
//        return promptLabel
//    }()
//    
//    private lazy var exitButton: NSButton = {
//        var exitButton = NSButton(frame: NSRect.zero)
//        exitButton.setButtonType(.momentaryLight)
//        exitButton.title = "Exit"
//        exitButton.target = self
//        exitButton.action = #selector(self.exitButtonClicked(btn:))
//        exitButton.isHidden = true
//        return exitButton
//    }()
//    
//    private lazy var noMoreButton: NSButton = {
//        var noMoreButton = NSButton(frame: NSRect.zero)
//        noMoreButton.setButtonType(.momentaryLight)
//        noMoreButton.title = "No show anymore"
//        noMoreButton.target = self
//        noMoreButton.action = #selector(self.noMoreShowButtonClicked(btn:))
//        noMoreButton.isHidden = true
//        return noMoreButton
//    }()
//
    
    override init(frame frameRect: NSRect) {
        super.init(frame: frameRect)
        // Drawing code here.
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func draw(_ dirtyRect: NSRect) {
        super.draw(dirtyRect)
        
        createViews()
        
    }

}

// MARK: -  计时器逻辑
extension JCNSView {
    
    func startCountTimer() {
        if #available(OSX 10.12, *) {
            self.stopCountTimer()
            self.countTimer = Timer.scheduledTimer(withTimeInterval: TimeInterval(1.0), repeats: true, block: { (timer) in
                print("===============count定时事件响应了================")
                self.currentIndex = self.currentIndex - 1
                self.startTimerButton.title = "\(self.currentIndex)s后全屏"
            })
        } else {
            // Fallback on earlier versions
        }
    }
    
    func stopCountTimer() {
        self.currentIndex = 5
        self.countTimer?.invalidate()
        self.countTimer = nil
    }
        
    func startTimer() {
        if #available(OSX 10.12, *) {
            self.stopTimer()
            self.startCountTimer()
            self.timer = Timer.scheduledTimer(withTimeInterval: TimeInterval(5), repeats: true, block: { (timer) in
                print("===============定时事件响应了================")
                self.timerEventToFullScreen()
                self.stopCountTimer()
            })
        } else {
            // Fallback on earlier versions
        }
    }
    
    @objc func reStartTimer() {
        self.startTimer()
    }
    
    func stopTimer() {
        self.timer?.invalidate()
//        self.timer = nil
    }
    
    @objc func timerEventToFullScreen() {
        guard let screen = NSScreen.main else { return }
        if !self.isInFullScreenMode {
            self.enterFullScreenMode(screen, withOptions: [NSView.FullScreenModeOptionKey.fullScreenModeAllScreens : true])
            self.stopTimer()
            self.startTimerButton.isHidden = true
            // 展示fullimage
            self.fullImage.isHidden = false
            self.fullImage.frame = screen.frame
            // 1s后显示一个提示框
            DispatchQueue.global().asyncAfter(deadline: DispatchTime.now() + 1) {
                DispatchQueue.main.async {
                    self.setupViewBackgroundColor(color: NSColor(red: 0.9, green: 0.6, blue: 0.6, alpha: 1.0))
                    self.showAlert()
                }
            }
        }
        
    }
}

// MARK: - 视图属性相关
extension JCNSView {
    
    func createViews() {
        self.addSubview(self.startTimerButton)
        self.addSubview(self.fullImage)
    }
    
    // 全屏后加一个弹窗
    func showAlert() {
        let alert = NSAlert()
        
        alert.addButton(withTitle: "Exit")
        alert.addButton(withTitle: "Not show more")
        alert.messageText = "Tips"
        alert.informativeText = "It's time to take a rest"
        
//        alert.alertStyle = NSAlert.Style.informational
        alert.alertStyle = NSAlert.Style.warning
        alert.beginSheetModal(for: self.window!) { (returnCode) in
            switch returnCode {
            case .alertFirstButtonReturn:
                self.exitButtonAction()
            case .alertSecondButtonReturn:
                self.noMoreShowButtonAction()
            default:
                print("")
            }
        }
        
        self.alert = alert
        
    }
    
    func showStartTimerButton() {
        DispatchQueue.main.async {
            self.startTimerButton.title = "Start Timer"
            self.startTimerButton.isHidden = false
            self.startTimerButton.frame = NSRect(x: 12, y: 12, width: 100, height: 40)
        }
    }
}

// MARK: - 子视图按钮事件
extension JCNSView {
    
    func exitButtonAction() {
        self.showStartTimerButton()
        self.exitFullSc()
        self.reStartTimer()
        self.startCountTimer()
        self.fullImage.isHidden = true
    }
    
    @objc func exitButtonClicked(btn: NSButton) {
        self.exitButtonAction()
    }
    
    func noMoreShowButtonAction() {
        self.showStartTimerButton()
        self.exitFullSc()
        self.timer?.invalidate()
        self.timer = nil
        self.fullImage.isHidden = true
    }

    @objc func noMoreShowButtonClicked(btn: NSButton) {
        self.noMoreShowButtonAction()
    }
        
    func exitFullSc() {
        if self.isInFullScreenMode {
            self.exitFullScreenMode(options: [NSView.FullScreenModeOptionKey.fullScreenModeAllScreens : true])
            self.setupViewBackgroundColor(color: NSColor(red: 0.8, green: 0.8, blue: 0.9, alpha: 1.0))
        }
    }
    

}

// MARK: - mouse事件
extension JCNSView {
    
    override func mouseDown(with event: NSEvent) {
        // 鼠标按下时改变背景颜色
        self.setupViewBackgroundColor(color: NSColor(red: 0.9, green: 0.6, blue: 0.6, alpha: 1.0))
    }
    
    override func mouseUp(with event: NSEvent) {
        // 鼠标松了恢复原来的颜色
        self.setupViewBackgroundColor(color: NSColor(red: 0.8, green: 0.8, blue: 0.9, alpha: 1.0))
    }
    
    override func mouseEntered(with event: NSEvent) {
        // 鼠标进入悬停
    }
    
}
